from flask import Blueprint, request, current_app
from flask_json import as_json
from flask_jwt_extended import jwt_required

from app import db
from app.models import CommonResult, IpFilter
from app.form.ip_filter_form import IpFilterForm
from .is_staff_user import is_staff_user
from app.auth.auth_decorator import has_role
from app.common.enums import RoleCodeEnum

log = current_app.logger
ip_filter = Blueprint('admin_ip_filter', __name__, url_prefix='/admin/ip')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(ip_filter)


# 列表查询
@ip_filter.post('/list')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def ip_filter_list():
    data_list = IpFilter.query.all()
    return CommonResult(data=data_list)


# 获取详情
@ip_filter.get('/get/<int:ip_filter_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(ip_filter_id):
    ip_filter_info = IpFilter.query.get(ip_filter_id)
    if ip_filter_info is None:
        return CommonResult(code=500, msg='记录不存在')
    return CommonResult(data=ip_filter_info, msg='获取成功')


# 添加记录
@ip_filter.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    IpFilterForm().api_validate()
    data = request.get_json()
    # 填充数据
    record = IpFilter()
    record.__dict__.update(data)
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


# 修改信息
@ip_filter.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    IpFilterForm().api_validate()
    data = request.get_json()
    # 根据ip查询记录，校验记录是否存在
    ip_filter_id = int(data.get('id'))
    record = IpFilter.query.get(ip_filter_id)
    if record is None:
        return CommonResult(code=500, msg='修改的记录不存在')
    db.session.query(IpFilter).filter(IpFilter.id == ip_filter_id).update(data)
    db.session.commit()
    return CommonResult(data=data, msg='修改成功')


# 删除记录
@ip_filter.get('/delete/<int:ip_filter_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(ip_filter_id):
    # 判断分类是否存在
    record = IpFilter.query.get(ip_filter_id)
    if record is None:
        return CommonResult(code=500, msg='删除的记录不存在')
    # 删除记录
    db.session.delete(record)
    db.session.commit()
    return CommonResult(msg='删除成功')
